package com.kkb.controller;

import com.kkb.pojo.User;
import com.kkb.vo.ResultVO;
import com.kkb.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import static com.alibaba.druid.sql.ast.SQLPartitionValue.Operator.List;


@Controller
@RequestMapping("admin")
@ResponseBody
public class AdminController {
    @Resource
    UserService userService;

    @RequestMapping("login")
    public ResultVO login(String username, String password, String code, HttpServletRequest request) throws ServletException, IOException {
        Object stored = request.getSession().getAttribute("code");
        if (stored == null)
            return new ResultVO(404, "请先获取验证码!");

        String storedCode = String.valueOf(stored);
        if (!storedCode.equals(code))
            return new ResultVO(404, "验证码错误!");

        User user = userService.queryByUserAndPass(username, password);
        if (user == null) {
            return new ResultVO(404, "用户名或密码错误!");
        }
        request.getSession().setAttribute("uid", user.getId());
        request.getSession().setAttribute("username", user.getUsername());

        return new ResultVO(user);
    }


    @RequestMapping("code")
    public ResultVO code(HttpServletRequest request) {
        int random = (int) (Math.floor(Math.random() * 9000) + 1000);
        request.getSession().setAttribute("code", random);
        return new ResultVO(random);
    }

    @RequestMapping("logout")
    public ResultVO logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return new ResultVO("登出成功!");
    }

    @RequestMapping("userInfo")
    public ResultVO userInfo(HttpServletRequest request) {
        Object username = request.getSession().getAttribute("username");
        Object uid = request.getSession().getAttribute("uid");
        if (username == null)
            return new ResultVO(404, "获取用户信息失败");
        else
            return new ResultVO(new ArrayList(Arrays.asList(username, uid)));
    }
}
